package ua.edu.nuos.jeetraining2012.cms.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * PersistenceConnector class.
 * <p/>
 * Define connector to DB. Predefined persistence unit cmsPU should exists.
 * To get the connection EntityManager, please use PersistenceConnector.getInstance().getEm();
 *
 * @author Victor N. Ganichev victor.ganichev@gmail.com
 * @version 1.0 Date: 23.04.13 Time: 23:03
 * @since 1.0
 */
public class PersistenceConnector {

    /**
     * Define own instance.
     */
    private static PersistenceConnector instance = null;

    /**
     * Define EntityManagerFactory instance.
     */
    private static EntityManagerFactory factory = null;

// Constructor

    /**
     * Private constructor for Singleton pattern.
     */
    private PersistenceConnector() {
        createFactory();
    }


    /**
     * Instantiate EntityManagerFactory object
     *
     * @return EntityManagerFactory instantiated object
     */
    protected EntityManagerFactory createFactory() {
        factory = Persistence.createEntityManagerFactory("cmsPU");
        return factory;
    }

    /**
     * Singleton instance return.
     *
     * @return PersistenceConnector instance
     */
    public static PersistenceConnector getInstance() {
        if (instance == null) {
            instance = new PersistenceConnector();
        }
        return instance;
    }

    /**
     * Return EntityManagerFactory instance
     *
     * @return EntityManagerFactory instance
     */
    protected EntityManagerFactory getFactory() {
        return factory;
    }

    /**
     * Return EntityManager instance.
     *
     * @return EntityManager instance.
     */
    public EntityManager getEm() {
        EntityManager em = null;
        EntityManagerFactory factory = getFactory();
        if (factory != null && factory.isOpen()) {
            em = factory.createEntityManager();
        } else {
            factory = createFactory();
            em = factory.createEntityManager();
        }
        return em;
    }

}
